<?php
    include         '../data/address_dal.php';
    include_once    '../entity/address_entity.php';

    class AddressMng
    {
        function update($addressEntity)
        {
            $addressDAL = new AddressDAL();
            if ($this->valiate($addressEntity->id, $addressEntity->name)) {
                if ($result = $addressDAL->update($addressEntity->id, $addressEntity->userID, $addressEntity->name, $addressEntity->address1, $addressEntity->address2, $addressEntity->address3,
                                                    $addressEntity->city, $addressEntity->country, $addressEntity->province, $addressEntity->zipCode, $addressEntity->inTime, $addressEntity->inUser)) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }

        function get($id)
        {
            $addressDAL = new AddressDAL();
            $where = "id = " . $id;
            if ($result = $addressDAL->get($where)) {
                $row = $result->fetch_assoc();
                $addressEntity = new AddressEntity();
                foreach ($row as $key => $value) {
                    $addressEntity->$key = $value;
                }
                return $addressEntity;
            } else {
                return false;
            }
        }

        function getAll($start, $pageSize, $sortField, $sortDirection)
        {
            switch($pageSize) {
                case "-1":
                    $orderBy = "-1";
                    break;
                case "-2":
                    $orderBy ="-2";
                    break;
                default:
                    $orderBy =" WHERE id = " . $_SESSION['userID'] . " ORDER BY " . $sortField . " " . $sortDirection . " LIMIT " . $start . ", " . ($pageSize * ($start + 1));
                    break;
            }
            
            $addressDAL = new AddressDAL();
            if ($result = $addressDAL->getAll($orderBy)) { 
                while($row = $result->fetch_assoc()) {
                    $addressList[] = $row;
                }
                return $addressList;
            } else { 
                return false;
            }
        }

        function delete($id)
        {
            $addressDAL = new AddressDAL();
            return ($addressDAL->delete($id));
        }

        function valiate($id, $name)
        {
            $addressDAL = new AddressDAL();
            return ($addressDAL->validate($id, $name));
        }
    }

?>
